package com.say.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.Date;

import com.say.receiver.ClickReceiver;
import com.say.test.R;
import com.say.tool.Tool;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

public class NotifyActivity extends Activity {
	LinearLayout ll;
	private ViewGroup.LayoutParams lpwrap;
	private TextView tv;
	private Context context;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ll = new LinearLayout(this);
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(-1, -1);
		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setGravity(Gravity.RIGHT);
		ll.setLayoutParams(lp);
		setContentView(ll);
		lpwrap = new ViewGroup.LayoutParams(-2, -2);
		
		OnClickListener l = new OnClickListener() {
			int a = 1;
			public void onClick(View v) {
				Tool.logInfo("哈哈");
				sendNotification(a);
//				notify4();
				/*
				if (++a % 2 == 1) {
					sendNotification(a);
				} else {
					createNotification(a);
				}*/
			}
		};
		addButton("发送一个普通通知", l);
		OnClickListener l1=  new View.OnClickListener() {
			public void onClick(View v) {
				String str = " TODO Auto-generated method stub";
				String [] ss = str.split(" ");
				sleepTask = new SleepTask();
				sleepTask.execute(ss);
			}
		};
		OnClickListener stopL=  new View.OnClickListener() {
			public void onClick(View v) {
				if(!sleepTask.isCancelled()) sleepTask.cancel(true);
			}
		};
		addButton("启动一个异步任务", l1);
		addButton("暂停这个异步任务", stopL);
		
		
		tv = new TextView(this);
		tv.setText("开始任务");
		ll.addView(tv, lpwrap);
	}
	SleepTask sleepTask;
	private class SleepTask extends AsyncTask<String, Integer, Integer> {
		@Override
		protected Integer doInBackground(String... params) {
			int count = params.length;
			int totalSize = 0;
			for (int i = 0; i < count; i++) {
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
				}
				totalSize += 1;
				publishProgress((int) ((i / (float) count) * 100));
			}
			return totalSize;
		}
		@Override
		protected void onPostExecute(Integer result) {
			System.out.println("onPostExecute:"+result);
			tv.setText("onPostExecute:"+result);
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			System.out.println("onProgressUpdate:"+values[0]);
			tv.setText("onProgressUpdate:"+values[0]+",length:"+values.length);
		}
		@Override
		protected void onPreExecute() {
			System.out.println("onPreExecute");
			tv.setText("onPreExecute");
		}
		@Override
		protected void onCancelled(Integer result) {
			System.out.println("onCancelled:"+result);
			tv.setText("onCancelled:"+result);
		}
	}

	private Button addButton(String text,View.OnClickListener listener){
		Button but = new Button(this);
		but.setText(text);
		but.setOnClickListener(listener);
		ll.addView(but, lpwrap);
		return but;
	}
	public void sendNotification(int num) {

		/**
		 * Create an intent that will be fired when the user clicks the
		 * notification. The intent needs to be packaged into a
		 * {@link android.app.PendingIntent} so that the notification service
		 * can fire it on our behalf.
		 */
		Intent clickIntent;
		PendingIntent pendingIntent ;
		clickIntent = new Intent(this, ClickReceiver.class);  
		pendingIntent = PendingIntent.getBroadcast(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		// BEGIN_INCLUDE (build_notification)
		Notification.Builder builder = new Notification.Builder(this);
		builder.setSmallIcon(android.R.drawable.ic_delete);
		InputStream in=null;
		try {
			in = getResources().getAssets().open("ic_fj.png");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Bitmap bm = BitmapFactory.decodeStream(in);
		builder.setLargeIcon(bm);
		builder.setTicker("Ticker text haha  ");
		// Set the intent that will fire when the user taps the notification.
		builder.setContentIntent(pendingIntent);

		// Set the notification to auto-cancel. This means that the notification
		// will disappear
		// after the user taps it, rather than remaining until it's explicitly
		// dismissed.
		builder.setAutoCancel(true);

		/**
		 * Build the notification's appearance. Set the large icon, which
		 * appears on the left of the notification. In this sample we'll set the
		 * large icon to be the same as our app icon. The app icon is a
		 * reasonable default if you don't have anything more compelling to use
		 * as an icon.
		 */
		// builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),
		// R.drawable.ic_launcher));
		/**
		 * Set the text of the notification. This sample sets the three most
		 * commononly used text areas: 1. The content title, which appears in
		 * large type at the top of the notification 2. The content text, which
		 * appears in smaller text below the title 3. The subtext, which appears
		 * under the text on newer devices. Devices running versions of Android
		 * prior to 4.2 will ignore this field, so don't use it for anything
		 * vital!
		 */
		builder.setContentTitle("BasicNotifications Sample");
		builder.setContentText("Time to learn about notifications!");
		builder.setSubText("Tap to view documentation about notifications.");

		// END_INCLUDE (build_notification)

		/**
		 * Send the notification. This will immediately display the notification
		 * icon in the notification bar.
		 */
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(num, builder.build());
		bm.recycle();
//		IntentFilter filter = new IntentFilter(NotificationManager.);
//		context.registerReceiver(receiver, filter)
	}

	/**
	 * A numeric value that identifies the notification that we'll be sending.
	 * This value needs to be unique within this app, but it doesn't need to be
	 * unique system-wide.
	 */
	private void createNotification(int num) {

		Notification.Builder builder = new Notification.Builder(this);

		// Create Intent to launch this Activity again if the notification is
		// clicked.
		Intent i = new Intent(this, MainActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(this, 0, i,
				PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(intent);

		// Sets the ticker text
		builder.setTicker(" ticker text 2222");

		// Sets the small icon for the ticker
		builder.setSmallIcon(android.R.drawable.ic_dialog_email);

		// Cancel the notification when clicked
		builder.setAutoCancel(true);

		// Build the notification
		Notification notification = builder.build();
//		getResources().
	
		// Inflate the notification layout as RemoteViews
//		RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.notification);
		
//		R.layout.notification_template_material_base
//		 contentView.setImageViewResource(viewId, srcId);
//		 contentView.setImageViewBitmap(viewId, bitmap);

//		notification.contentView = contentView;


		// START_INCLUDE(notify)
		// Use the NotificationManager to show the notification
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.notify(num, notification);
//		 android.R.layout.n;  
//		nm.can
	}

	void notify4() {
		int layout_nofify=0,icon = 0;
		try {
//			 RemoteViews contentView = new RemoteViews(getPackageName(),  
//			            R.layout.notification_template_base);  
			Class<?> clazz;
//			com.android.internal;
			clazz = Class.forName("com.android.internal.R$layout");
			Field field = clazz.getField("notification_template_base");
			field.setAccessible(true);
			layout_nofify = field.getInt(null);
			System.out.println("1:"+layout_nofify);
//			01-29 23:58:49.551: I/System.out(5412): 1:16908294
//			01-29 23:58:49.552: I/System.out(5412): 2:2131165215
			clazz = Class.forName("com.android.internal.R$id");
			field = clazz.getField("icon");
			field.setAccessible(true);
			icon = field.getInt(null);
			System.out.println(icon);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String s = getPackageName();
		System.out.println(s);
		RemoteViews view = new RemoteViews(getPackageName(), layout_nofify);
		System.out.println("view:"+view);
		Bitmap bm = null;
		bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

		view.setImageViewBitmap(icon, bm);
		Notification no = new Notification();
//		no.contentView=view;
		no.when = System.currentTimeMillis();
		no.tickerText = "view view";
		NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.notify(1000, no);
	}
	private void notify3() {
			//1得到一个notificationManager
			//得到一个notification的服务
			 NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			 //2Instantiate  the Notification
			 Notification  notification=new Notification(R.drawable.ic_launcher, "tickerText", System.currentTimeMillis());
			 
			 notification.sound=Uri.fromFile(new File("/sdcard/haha.mp3"));//指定声音
			 notification.flags=Notification.FLAG_AUTO_CANCEL;//notification显示完自动清空
			 notification.flags=Notification.FLAG_NO_CLEAR;//notification图标永远存在
			 notification.vibrate=new long[]{1000,200,1000};
			 
			 
			 
			 //3define the  notification's manager and RendingIntent//pendingIntnet延期的意图
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		notification.setLatestEventInfo(this, "notife 标题", "notification 正文", contentIntent);
		// pass the Notification to the notificatiion
		manager.notify(0, notification);

	}
}
